const {startJob, cancel, list, startBusinessJob} = require('./Tasks')
const apiModule = require('./api')
let global = null
let api = null

async function handler(request) {
    // console.log(request.payload)
    //发送人
    let senderId = request.payload.senderId
    let text = request.payload.text.content
    let result = ''
    //登陆
    if (text.indexOf('/login') > -1) {
        result = await login(text, senderId)
    } else if (text.indexOf('/setUrl') > -1) {
        result = await setUrl(text)
    } else if (text.indexOf('/scheduleJob') > -1) {
        result = await scheduleJob(text)
    } else if (text.indexOf('/startBusiness') > -1) {
        result = await startBusiness(text, senderId)
    } else if (text.indexOf('/cancelJob') > -1) {
        result = await cancelJob(text)
    } else if (text.indexOf('/jobList') > -1) {
        result = await jobList(text)
    } else if (text.indexOf('/help') > -1) {
        result = await help(text)
    } else {
        result = 'no thing'
    }


    //机器人回复
    return {"at": {"isAtAll": false}, "text": {"content": result}, "msgtype": "text"};
}

/**
 * 登陆接口
 *
 * @param text
 * @returns {Promise<unknown>}
 */
async function login(text, senderId) {
    return new Promise(async resolve => {
        if (!global.getBaseUrl()) {
            resolve('base_url not set done error')
        } else {
            let params = removeFuncName(text, '/login').trim().split('##')
            let ee = await api.loginByUp(JSON.parse(params[2]))
            let r = ee.data
            console.log(`login result ==>  ${JSON.stringify(r)}`)
            if (r.returnCode == 100) {
                global.setSession(senderId, r.returnData.token)
                global.setParams(r.returnData.token + '_login', JSON.parse(params[2]))
                let getInfo = await api.getInfo(r.returnData.token)
                console.log(JSON.stringify(getInfo.data))
                resolve('登陆成功')
            } else {
                resolve(r)
            }

        }

    })
}


/**
 * 设置 任务调度接口base url
 *
 * @param text
 * @returns {Promise<void>}
 */
async function setUrl(text) {
    return new Promise(resolve => {
        let params = removeFuncName(text, '/setUrl')
        global.setBaseUrl(params)
        resolve('setUrl ok')
    })
}

async function scheduleJob(text) {

    return new Promise(resolve => {
        let params = removeFuncName(text, '/scheduleJob')
        let ps = params.split('#')
        resolve(startJob(ps[0], ps[1]))
    })
}

async function cancelJob(text) {

    return new Promise(resolve => {
        let params = removeFuncName(text, '/cancelJob')
        cancel(params)
        resolve('cancelJob ok')
    })
}

async function jobList(text) {
    return new Promise(resolve => {
        resolve(list())
    })
}

async function help() {
    return new Promise(resolve => {
        let str = '/scheduleJob cron#url\n'
        str += '/cancelJob name \n'
        str += '/jobList  \n'
        resolve(str)
    })
}

async function startBusiness(text, senderId) {
    return new Promise(resolve => {
        if (global.getSession(senderId)) {
            let params = removeFuncName(text, '/startBusiness').trim().split('##')


            startBusinessJob(params[1],
                global.getBaseUrl() + params[2],
                JSON.parse(params[3]),
                senderId,
                global,
                api,
            )
            resolve('startBusiness ok')
        } else {
            resolve('login error')
        }
    })
}

function removeFuncName(text, name) {
    return text.replace(name, '').trim()
}

function setGlobal(_global) {
    global = _global
    api = new apiModule(global)
}

module.exports = {
    handler, setGlobal
}
